﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;

namespace Bzure.Mvc.ResourceAccess
{

    /**/
    /// <summary>
    /// 防盗链Filter.
    /// </summary>
    public class AntiOutSiteLinkAttribute : ActionFilterAttribute, IActionFilter
    {

        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContextBase httpContext = filterContext.HttpContext;
            if (null != httpContext.Request.UrlReferrer)
            {
                string serverDomain = httpContext.Request.Url.Host;
                string refDomain = httpContext.Request.UrlReferrer.Host;
                if (GetRootDomain(refDomain).Equals(GetRootDomain(serverDomain), StringComparison.OrdinalIgnoreCase))
                {
                    return;//如果根域名相同就返回
                }
            }

            Bitmap bmp = new Bitmap(200, 50);
            Graphics g = Graphics.FromImage(bmp);

            g.FillRectangle(Brushes.White, 0, 0, 200, 50);
            g.DrawString("请不要盗链", new Font("Arial", 15), Brushes.Red, new PointF(0, 0));
            filterContext.Result = new ImageResult() { Image = bmp, ImageFormat = ImageFormat.Gif };
        }



        /**/
        /// <summary>
        /// 获取网站的根域名
        /// </summary>
        /// <param name="domain">网站的域名，不带"Http://"</param>
        /// <returns></returns>
        private string GetRootDomain(string domain)
        {
            if (string.IsNullOrEmpty(domain))
            {
                throw new ArgumentNullException("参数'domain'不能为空");
            }
            string[] arr = domain.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            if (arr.Length <= 2)
            {
                return domain;
            }
            else
            {
                return arr[arr.Length - 2] + "." + arr[arr.Length - 1];
            }
        }
    }




}
